
#include "../../../include/buffer.h"
#include "../../../include/core.h"
#include "../../../include/session.h"
#include "../../../include/server.h"
#include "../../../include/mylog.h"

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <signal.h>

static void handleConnection(struct session* session, void* privateData) {
	mylog(LOG_INFO, "onConnection");
}

static RetHandle handleData(struct session* session, void* privateData) {
	mylog(LOG_INFO, "handleData!!!!");
	if (!session) {
		return CLOSE_HANDLE;
	}

	int readableBytes = getReadableBytesBuffer(session->readBuffer);
	char* sendBuf = (char *)zmalloc(readableBytes + 1);
	memcpy(sendBuf, getReadIndexBuffer(session->readBuffer), readableBytes);
	writeSession(session, sendBuf, readableBytes);
	moveReadIndexBuffer(session->readBuffer, readableBytes);
	zfree(sendBuf);
	return CONTINUE_HANDLE;
}

static void handleDisConnection(struct session* session, void* privateData) {
	mylog(LOG_INFO, "onDisConnection");
}


struct core* c = NULL;
void onSigInt(int sig) {
	mylog(LOG_NOTICE, "onSigInt");
	if (c) {
		mylog(LOG_INFO, "=========");
		stopCore(c);
	}
}


int main(){

	signal(SIGINT, onSigInt);
	int workThreadNum = 4;
	c = initCore(workThreadNum, 1);
	if (!c) {
		mylog(LOG_INFO, "init core error!!");
		exit(-1);
	}

	char err[1024];
	int port = 1208;
	char* bindaddr = "127.0.0.1";
	struct server* server = initServer(c , err, port, bindaddr);
	if (!server) {
		mylog(LOG_INFO, "init server error!!!");
		destroyCore(c );
		exit(-2);
	}

	server->serverCallBack->onConnectionCallBack = handleConnection;
	server->serverCallBack->onDataCallBack = handleData;
	server->serverCallBack->onDisConnectionCallBack = handleDisConnection;

	if (addServerCore(c , server) != 0) {
		mylog(LOG_INFO, "add server error!!!");
		destroyServer(server);
		destroyCore(c);
		exit(-3);
	}

	mylog(LOG_INFO, "test1 startserver!!!");
	eventLoopCore(c );
	mylog(LOG_INFO, "test1 endserver!!!!");

	destroyCore(c);
	return 0;
}
